﻿@page "/Downloads"
@using HardHatCore.HardHatC2Client.Components;
@using HardHatCore.HardHatC2Client.Models
@using HardHatCore.HardHatC2Client.Services
@using System.Reflection
@inject IJSRuntime JS

<CascadingAuthenticationState>
    <AuthorizeView Roles="Operator,TeamLead">
        <Authorized>
        
            <h3 class="text-center">Downloads</h3>
            <div class="container-fluid" style="height:500px; overflow-y:scroll">
                <div class="row">
                    <div class="col-md-12">
                        <style>
            .selected 
            {
                background-color: #1E88E5 !important;
            }
            .selected > td 
            {
                color: white !important;
            }   
            .selected > td .mud-input 
            {
                color: white !important;
            }
            </style>
                        <MudTable Virtualize="true" Items="@DownloadedFiles" HorizontalScrollbar="true" FixedHeader="true" Height="400px" Hover="true" Dense="true" Outlined="true" Striped="true" RowClassFunc="@SelectedRowClassFunc" OnRowClick="RowClickEvent" @ref="mudTable" T="DownloadFile">
                            <HeaderContent>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Name </MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Host</MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Original Path </MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Saved Location</MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Download Time</MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Download</MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">View</MudTh>
                            </HeaderContent>
                            <RowTemplate Context="Rowcontext">
                                <MudTd>@Rowcontext.Name</MudTd>
                                <MudTd>@Rowcontext.Host</MudTd>
                                <MudTd>@Rowcontext.OrginalPath</MudTd>
                                <MudTd>@Rowcontext.SavedPath</MudTd>
                                <MudTd>@Rowcontext.downloadedTime</MudTd>
                                <MudTd>
                                    <MudIconButton Icon="@Icons.Material.Filled.Save" Color="Color.Primary" Size="Size.Small" @onclick="@HandleDownload"></MudIconButton>
                                </MudTd>
                                <MudTd>
                                    <MudIconButton Icon="@Icons.Material.Filled.Visibility"Color="Color.Primary" Size="Size.Small" @onclick="() => HandleView(Rowcontext.SavedPath,Rowcontext.Name)"></MudIconButton>
                                </MudTd>
                            </RowTemplate>
                        </MudTable>
                    </div>
                </div>
            </div>

            @if (showSuccessCallAlert)
            {
                <MudAlert Class="mt-16" Severity="Severity.Success" Variant="Variant.Outlined" ContentAlignment="HorizontalAlignment.Center" ShowCloseIcon="true" CloseIconClicked="(() => CloseMe(true))">@mudTable.SelectedItem.Name downloaded, check downloads dir inside the client folder.</MudAlert>
            }
            @if (showWarningCallAlert)
            {
                <MudAlert Class="mt-16" Severity="Severity.Warning" Variant="Variant.Outlined" ContentAlignment="HorizontalAlignment.Center" ShowCloseIcon="true" CloseIconClicked="(() => CloseMe(false))">Failed to download file or no file selected. Check terminal for errors.</MudAlert>
            }

        </Authorized>
    </AuthorizeView>
    <AuthorizeView Roles="Guest">
        <Authorized>
            <h3 class="text-center">Downloads</h3>
            <div class="container-fluid" style="height:500px; overflow-y:scroll">
                <div class="row">
                    <div class="col-md-12">
                        <style>
                .selected 
                {
                    background-color: #1E88E5 !important;
                }
                .selected > td 
                {
                    color: white !important;
                }   
                .selected > td .mud-input 
                {
                    color: white !important;
                }
                </style>
                        <MudTable Virtualize="true" Items="@DownloadedFiles" HorizontalScrollbar="true" FixedHeader="true" Height="400px" Hover="true" Dense="true" Outlined="true" Striped="true" RowClassFunc="@SelectedRowClassFunc" OnRowClick="RowClickEvent" @ref="mudTable" T="DownloadFile">
                            <HeaderContent>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Name </MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Host</MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Original Path </MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Saved Location</MudTh>
                                <MudTh Style="@setStyle(Settings.IsCheckedBox)">Download Time</MudTh>
                            </HeaderContent>
                            <RowTemplate Context="Rowcontext">
                                <MudTd>@Rowcontext.Name</MudTd>
                                <MudTd>@Rowcontext.Host</MudTd>
                                <MudTd>@Rowcontext.OrginalPath</MudTd>
                                <MudTd>@Rowcontext.SavedPath</MudTd>
                                <MudTd>@Rowcontext.downloadedTime</MudTd>
                            </RowTemplate>
                        </MudTable>
                    </div>
                </div>
            </div>
        </Authorized>
    </AuthorizeView>
     <AuthorizeView Roles="TeamLead,Operator,Guest">
                   <NotAuthorized>
                        <h1 class="text-center">Not Authorized</h1>
                        <UnAuthorizedDialogBox></UnAuthorizedDialogBox>
                    </NotAuthorized>
        </AuthorizeView>
</CascadingAuthenticationState>

@code {

    [Inject]
    private IDialogService DialogService { get; set; }
    public static List<DownloadFile> DownloadedFiles = new List<DownloadFile>();
    private MudTable<DownloadFile> mudTable;
    private int selectedRowNumber = -1;
    private bool showSuccessCallAlert = false;
    private bool showWarningCallAlert = false;

    private void CloseMe(bool value)
    {
        if (value)
        {
            showSuccessCallAlert = false;
        }
        else
        {
            showWarningCallAlert = false;
        }
    }

    private string setStyle(bool IsDark)
    {
        if(IsDark)
        {
            return "background:white; color:black;";
        }
        return "background:#333333; color:white;"; 
    }

    private string SelectedRowClassFunc(DownloadFile file, int rowNumber)
    {
        if (mudTable.SelectedItem != null && mudTable.SelectedItem.Equals(file))
        {
            selectedRowNumber = rowNumber;
            return "selected";
        }
        else
        {
            return string.Empty;
        }
    }

    private void RowClickEvent(TableRowClickEventArgs<DownloadFile> tableRowClickEventArgs)
    {
    }

    private async Task HandleDownload()
    {
        try
        {
            if (mudTable.SelectedItem != null)
            {
                var file = mudTable.SelectedItem;
                var path = file.SavedPath;
                var name = file.Name;
                //cause a file browser popup to save the file
                var fileContentString = await HardHatHubClient._hub.TriggerDownload(path);
                var fileContent = Convert.FromBase64String(fileContentString);

                char allPlatformPathSeperator = Path.DirectorySeparatorChar;
                // find the Engineer cs file and load it to a string so we can update it and then run the compiler function on it
                string dirpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                //split path at bin keyword
                string[] pathSplit = dirpath.Split("bin"); //[0] is the parent folder [1] is the bin folder
                                                           //update each string in the array to replace \\ with the correct path seperator
                pathSplit[0] = pathSplit[0].Replace("\\", allPlatformPathSeperator.ToString());

                System.IO.File.WriteAllBytes(pathSplit[0] + "Downloads" + $"{allPlatformPathSeperator}{name}", fileContent);
                showSuccessCallAlert = true;
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
            showWarningCallAlert = true;
        }
    }
    public static async Task HandleDownload(string path, string name)
    {
        try
        {
            //cause a file browser popup to save the file
            var fileContentString = await HardHatHubClient._hub.TriggerDownload(path);
            var fileContent = Convert.FromBase64String(fileContentString);

            char allPlatformPathSeperator = Path.DirectorySeparatorChar;
            // find the Engineer cs file and load it to a string so we can update it and then run the compiler function on it
            string dirpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            //split path at bin keyword
            string[] pathSplit = dirpath.Split("bin"); //[0] is the parent folder [1] is the bin folder
                                                       //update each string in the array to replace \\ with the correct path seperator
            pathSplit[0] = pathSplit[0].Replace("\\", allPlatformPathSeperator.ToString());

            System.IO.File.WriteAllBytes(pathSplit[0] + "Downloads" + $"{allPlatformPathSeperator}{name}", fileContent);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    public async Task HandleView(string path, string name)
    {
        try
        {
            //cause a file browser popup to save the file
            var fileContentString = await HardHatHubClient._hub.TriggerDownload(path);
            var fileContent = Convert.FromBase64String(fileContentString);
            if (fileContent != null && fileContent.Length > 0)
            {
                string contentType = await DetermineFileContentType(name);
                //create a new MemoryStream object and pass the byte array to the constructor
                MemoryStream ms = new MemoryStream(fileContent);
                var dataUrl = $"data:{contentType};base64,{Convert.ToBase64String(fileContent)}";
                if (contentType.Equals("application/zip"))
                {
                    var dialogParameters = new DialogParameters
                        {
                            ["fileName"] = name,
                            ["fileData"] = ms
                        };
                    var dialogOptions = new DialogOptions
                        {
                            MaxWidth = MaxWidth.ExtraLarge,
                            FullWidth = true,

                        };
                    DialogService.Show<ViewDownloadedZipFile_Dialog>("Zip File", dialogParameters, dialogOptions);
                    return;
                }
                await MudExFileDisplayDialog.Show(DialogService, dataUrl, name, contentType, ex => ex.JsRuntime = JS);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            Implants.ShowErrorToast(ex.Message);
        }
    }


    public static async Task<string> DetermineFileContentType(string fileName)
    {
        string fileExtension = fileName.Split('.').Last();
        //based on the file extension return the correct content type
        switch (fileExtension)
                {
                    case "txt":
                        return "text/plain";
                    case "pdf":
                        return "application/pdf";
                    case "doc":
                        return "application/vnd.ms-word";
                    case "docx":
                        return "application/vnd.ms-word";
                    case "xls":
                        return "application/vnd.ms-excel";
                    case "xlsx":
                        return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    case "png":
                        return "image/png";
                    case "jpg":
                        return "image/jpeg";
                    case "jpeg":
                        return "image/jpeg";
                    case "gif":
                        return "image/gif";
                    case "csv":
                        return "text/csv";
                    case "zip":
                        return "application/zip";
                    default:
                        break;
                }
        return "";
    }
}